package com.example.gulimall.cart.controller;

import com.example.common.constant.AuthServerConstant;
import com.example.gulimall.cart.interceptor.CartInterceptor;
import com.example.gulimall.cart.service.CartService;
import com.example.gulimall.cart.vo.Cart;
import com.example.gulimall.cart.vo.CartItem;
import com.example.gulimall.cart.vo.UserInfoTo;
import org.springframework.aop.target.LazyInitTargetSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("/currentUserCartItems")
    @ResponseBody
    public List<CartItem> getCurrentCartItems(){
        return cartService.getCurrentCartItems();
    }


    @GetMapping("/cartlist")
    public String CartList(Model model) throws ExecutionException, InterruptedException {

        Cart cart = cartService.getCart();

        model.addAttribute("cart",cart);

        return "cartList";
    }


    // 这里防止重复刷新而导致的重复添加  所以用重定向的方式将添加操作和刷新操作分离
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num,
                            RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {

        cartService.addToCart(skuId,num);
        //redirect的addFlush那个方法是放在session里且只能用一次 这里是重复用 懂？
        redirectAttributes.addAttribute("skuId",skuId);
        return "redirect:http://cart.gulimall.com/addToCartSuccess";
    }

    @GetMapping("/addToCartSuccess")
    public String addToCartSuccess(@RequestParam("skuId") Long skuId, Model model){
        CartItem cartItem = cartService.getCartItem(skuId);
        model.addAttribute("item",cartItem);
        return "success";
    }

    @GetMapping("/checkItem")
    public String CheckItem(@RequestParam("skuId") Long skuId, @RequestParam("check") Integer check){
        cartService.checkItem(skuId,check);
        return "redirect:http://cart.gulimall.com/cartlist";
    }

    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId, @RequestParam("count") Integer count){
        cartService.countItem(skuId,count);
        return "redirect:http://cart.gulimall.com/cartlist";

    }

    @GetMapping("/delItem")
    public String delItem(@RequestParam("deleteId") Long deleteId){
        cartService.delItem(deleteId);
        return "redirect:http://cart.gulimall.com/cartlist";

    }
}
